package liuzhou.spark.common;

import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;

import java.io.IOException;

public class HbaseUtils {
    HBaseAdmin admin = null;
    Configuration configuration = null;


    //单例模式
    private HbaseUtils(){
        configuration = new Configuration();
        configuration.set("hbase.zookeeper.quorum","node1:2181,node2:2181,node3:2181");
        configuration.set("hbase.rootdir","hdfs://node1:8020/hbase");
        try {
            admin = new HBaseAdmin(configuration);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static HbaseUtils instance = null;

    public static synchronized HbaseUtils getInstance(){
        if (null == instance){
            instance = new HbaseUtils();
        }
        return instance;
    }

    /**
     * 根据表名获取htable实例
     * @param tableName
     * @return
     */
    public HTable getHTable(String tableName){
        HTable table = null;
        try {
            table = new HTable(configuration,tableName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 添加数据到表中
     * @param tbName
     * @param rowId
     * @param cf
     * @param col
     * @param value
     */
    public void put(String tbName,String rowId,String cf,String col,String value){
        HTable table = getHTable(tbName);
        Put put = new Put(Bytes.toBytes(rowId));
        put.add(Bytes.toBytes(cf),Bytes.toBytes(col),Bytes.toBytes(value));
        try {
            table.put(put);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //@Test
    public static void test01(){
        String tbName = "aqy_1";
        String id = "20190610_95";
        String cf = "info";
        String col = "class_click_count";
        String value = "700";

        HbaseUtils.getInstance().put(tbName,id,cf,col,value);
    }

    public static void main(String[] args) {
         test01();
    }
}
